// import { ShopOverPage } from './../shop-over/shop-over';
import { PIC_URL } from "./../../providers/Config";

// import { StyleService } from './../../providers/StyleService';
import { BasePage } from "./../basePage";
import { UserService } from "./../../providers/UserService";
import { StorageService } from "./../../providers/StorageService";
import { Component, Injector } from "@angular/core";
import {
  IonicPage,
  NavController,
  AlertController,
  ToastController,
  ActionSheetController,
  NavParams,
} from "ionic-angular";
import { StyleService } from "./../../providers/StyleService";

declare var $: any;
declare var cordova: any;
// import { StorageService } from './../../providers/StorageService';
/**
 * Generated class for the OrderPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

/**
 * 跳转到订单确认页面 要传过来的数据包括 购买的商品id  以及购买的数量，服务方式：是上门服务还是到店服务
 */

@IonicPage()
@Component({
  selector: "page-order",
  templateUrl: "order.html"
})

export class OrderPage {
  outTradeNo: any;

  market_price: any;
  service_name: any;
  picrooturl: string;
  shop_name: any;
  shop_logo: any;

  /*保存用户的电话*/
  user_phone: any;
  nickname: any;
  /*保存用户的 收货地址*/
  user_address: any;
  userinfo: any;
  toShop: boolean;
  toHome: boolean;
  // num: number=1;
  countService_price: any;
  service_price: any;
  num: any;
  unitPrice: any;
  choice: boolean;
  goods_id: any;
  service_pic = "";
  /*用来保存 用户的收货地址*/
  shopAddress: any;
  constructor(
    public navCtrl: NavController,
    private alertCtrl: AlertController,
    private actionCtrl: ActionSheetController,
    public toastCtrl: ToastController,
    public stc: StorageService,
    public styleService: StyleService,
    public userService: UserService,
    public navParams: NavParams
  ) {}
  submitAo = {
    user_id: null,
    book_type: null,
    book_time: null,
    service_count: null,
    total_price: null,
    service_id: null,
    book_address: ""
  };
  seller={}/*卖家信息*/ 
  ionViewDidLoad() {
    this.submitAo.total_price = this.countService_price = this.countService_price = this.service_price = this.navParams.get(
      "service_price"
    );
    this.submitAo.service_count = this.num = 1;
    this.choice = this.navParams.get("choice");
    this.unitPrice = this.service_price / this.num;
    this.submitAo.service_id = this.goods_id = this.navParams.get("goods_id");
    this.service_pic = this.navParams.get("service_pic");
    this.service_name = this.navParams.get("nail_name");
    this.market_price = this.navParams.get("market_price");
    this.userinfo = this.stc.read("userinfo");
    if (this.userinfo == null) {
      this.showAlert("请先登录");
      return;
    }

    this.submitAo.user_id = this.userinfo.user_id;
    this.user_phone = this.userinfo.user_phone;
    this.picrooturl = PIC_URL;
    console.log(this.navParams.data);
    console.log("当前的商品id" + this.goods_id);
   
    /*
      通过商品id 和用户id 查询商品信息  http://192.168.1.99:7777/admin/api/getBuyServiceAPI
      let res = await this.styleProvider.getBuyServiceAPI(this.data);
    */
    // this.getBuyServiceAPI();        //得到商品的信息
    this.myinfo();

    this.getShopInfoByServiceIdAPI(); //通过 service_id 得到店铺的信息

    /*通过用户的ID  获取到他的 默认收货地址*/
    let res = this.getUserAddress();
    console.log(res);
    console.log(this.unitPrice);
    console.log(this.service_price);
    console.log(this.num);
    console.log(this.choice);
    this.toHome = this.choice ? true : false;
    this.toShop = this.choice ? false : true;
    if (this.choice) {
      this.submitAo.book_type = 2;
    } else {
      this.submitAo.book_type = 1;
    }
  }

  ionViewWillEnter() {
    this.shopAddress = this.stc.read("shopAddress");
    let address = this.shopAddress;
    console.log(address);

    /*如果缓存地址里面存了 收货地址 就渲染到页面上*/
    if (this.shopAddress != null) {
      this.user_address = address.consignee_address + address.detail_address;
      this.nickname = address.consignee;
      this.user_phone = address.consignee_phone;
    }
  }
  Gopop() {
    this.navCtrl.pop({animate:false});
  }
/*跳转到二维码页面 */
  GoShopOver(){
    this.navCtrl.push("ShopOverPage",this.seller);
    console.log(this.seller)
  }
  /*  减少购买数量**/
  reduceNum() {
    if (this.num > 1) {
      this.num--;
    } else {
      this.num = 1;
    }
    this.submitAo.service_count = this.num;
    this.submitAo.total_price = this.countService_price =
      this.unitPrice * this.num + ".00";
  }

  /* 增加购买数量**/
  plusNum() {
    this.num++;
    this.submitAo.service_count = this.num;
    this.submitAo.total_price = this.countService_price =
      this.unitPrice * this.num + ".00";
    
  }

  /** 上门服务 */
  isToHome() {
    this.toHome = true;
    this.toShop = false;
  }

  /** 到店服务 */
  isToShop() {
    this.toHome = false;
    this.toShop = true;
  }

  /**提交订单 */
  async submitOrder() {
    // 生成时间戳
    // var timestamp = Date.parse(new Date());
    var timestamp = new Date().getTime().toString();
    timestamp = timestamp.substr(0, 10);
    this.submitAo.book_time = timestamp;

    let res = await this.styleService.submitServiceOrderAPI(this.submitAo);
    console.log(res);
    // 生成订单成功  去支付
    if (res.error_code == 0) {
      this.outTradeNo = res.order_sn;
      let alert = this.alertCtrl.create({
        title: "确认支付",
        message: res.msg + "，请点击确认去支付",
        buttons: [
          {
            text: "取消",
            role: "cancel",
            handler: () => {
              console.log("Cancel clicked");
            }
          },
          {
            text: "确认支付",
            handler: () => {
              this.gotopay();
            }
          }
        ]
      });
      alert.present();
      console.log(res.order_sn);
    } else if (res.error_code == 1002) {
      this.toastCtrl
        .create({
          message: res.reason,
          duration: 3000,
          position: "middle"
        })
        .present();
    }
  }

  /**去支付 */
  gotopay() {
    this.actionCtrl
      .create({
        buttons: [
          {
            text: "支付宝支付",
            handler: () => {
              //let alipaystr = this.editOrderAPI(item);

              this.aliPay();
            }
          },
          {
            text: "微信支付",
            handler: () => {
              this.aliPay2();
            }
          },
          {
            text: "取消",
            role: "cancel"
          }
        ]
      })
      .present();
  }

  unescapeHTML(a) {
    //let aNew = "" + a;
    let str =
      "app_id=2016121504287738&biz_content=%7B%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22laravel%22%2C%22out_trade_no%22%3A%22SN23788%22%2C%22total_amount%22%3A120%2C%22body%22%3A%22%22%22seller_id%22%3A%2218827403620%40139.com%22%7D&charset=UTF-8&format=JSON&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F192.168.1.99%3A1114%2FAdmin%2FAlipay%2Fnotifyurl&sign_type=RSA&timestamp=2018-02-09+09%3A52%3A06&version=1.0&sign=jVC%2FjWMqeVaKTOM4mntqV6hiSUC1Kn5SVHG981up1taiUGCHIQpHAz%2BqEz9%2FSjNRLhoMNEaYJGRf4E5fmkjzM6MBPQkGywFabZ%2Fr%2Bk0t6Iyrq9AKu6i1O0STSzTjjAaS9y%2BaQpq5fSJ190FLVfKAzstYuhVUXkCNw%2B%2FWCff4dt8%3D";
    //return aNew.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, '"').replace(/'/g, "'");
    return str;
  }
  aliPay() {
    console.log(333);
		console.log(this.service_name);
    console.log(this.outTradeNo);
    console.log(this.service_price);
    console.log(this.num)
		console.log(this.service_price * this.num)
    console.log(333);
    $.post(
      "http://116.62.162.165:1228/api/alipay/uniformPayGateway",
      {
        subject: this.service_name,
        outTradeNo: this.outTradeNo,
        totalAmount: 0.01,
        // totalAmount: this.service_price * this.num,
        payType: 2
      },
      data => {
        //let payInfo=this.unescapeHTML(data);
        console.log(data);

        cordova.plugins.alipay.payment(data, success => {}, error => {});
      }
    );
  }

  aliPay2() {
    $.post(
      "http://192.168.1.99:1114/api/common/uniformPayer",
      {
        pay_type: 1,
        out_trade_no: "SN23788",
        subject: "laravel",
        total_amount: 0.01,
        alipay_type: 2
      },
      data => {
        //let payInfo=this.unescapeHTML(data);
        console.log(data);
        data = this.unescapeHTML(data);

        console.log(data);

        cordova.plugins.alipay.payment(data, success => {}, error => {});
      }
    );
  }

  /**获取用户名 */
  async myinfo() {
    let param = { user_id: this.userinfo["user_id"] };
    let result = await this.userService.doMyInfoAPI(param);
    console.log(result);
    if (result.code != 1) {
      let alert = this.alertCtrl.create({
        title: "确认",
        message: result.msg,
        buttons: [
          {
            text: "确认",
            handler: () => {
              console.log("Buy clicked");
            }
          }
        ]
      });
      alert.present();
    } else {
      // this.nickname = result.data.user_info.user_nickname;
    }
  }

  /**获取店铺名+店铺logo */
  async getShopInfoByServiceIdAPI() {
    let param = { service_id: this.goods_id };
    console.log(param);
    // let result = await this.userService.getShopInfoByServiceIdAPI(param);
    let result = await this.userService.getShopInfoByServiceIdAPI(param);
    console.log(result);
    this.shop_logo = result.data.shop_logo;
    this.shop_name = result.data.shop_name;
    this.seller=result.data
    console.log(result.data);
  }

  /*获取用户的默认的收货地址*/
  async getUserAddress() {
    // if(addressArr){

    // }
    let username = await this.userService.doPersonalInfoAPI({
      user_id: this.userinfo.user_id
    });
    console.log(username.data);

    this.nickname = username.data.user_nickname;
    // let result = await this.userService.getAddressListAPI({//这是获取默认地址  因为需求修改注释了
    //   user_id: this.userinfo.user_id
    // });
    // console.log(result);
    // if (result.data.length == 0) {
    //   // this.toChoiseAddress();
    // } else {
    //   let addressArr = result.data.filter(item => {
    //     return item.default_address == "1";
    //   })[0];
    //   console.log(addressArr);
    //   this.user_address =
    //     addressArr.consignee_address + addressArr.detail_address;
    //   this.nickname = addressArr.consignee;
    //   this.user_phone = addressArr.consignee_phone;
    // }
  }
  /*跳转到 选择收货地址的页面*/
  // toChoiseAddress() {
  //   console.log("跳转到选择收货地址的页面");
  //   this.navCtrl.push("ChoseAddressPage");
  // }

  showAlert(msg, title = "提示", callFunc = null) {
    let alert = this.alertCtrl.create({
      title: title,
      subTitle: msg,
      buttons: [
        {
          text: "确定",
          handler: data => {
            if (callFunc) {
              callFunc.apply(data);
            }
          }
        }
      ]
    });
    alert.present();
  }
}
